// 超时
var prisonAfterNDays = function(cells, N) {
    var result = new Array(8), day = 0;
    while(N>0){
        for(let i=0;i<cells.length;i++){
            if(i===0 || i===cells.length-1){
                result[i] = 0;
            } else if(cells[i+1]-cells[i-1]===0){
                result[i] = 1;
            } else{
                result[i] = 0;
            }
        }
        // 直接赋值就是深拷贝 先将数组转为字符串再转成数组即可
        cells = result.join().split(',');
        N--;
    }
    return cells;
};
// 
var prisonAfterNDays_2 = function(cells, N) {
    var result = new Array(8), day = 0, startCells = '', T = 0;
    while(day<N){
        for(let i=0;i<cells.length;i++){
            if(i===0 || i===cells.length-1){
                result[i] = 0;
            } else if(cells[i+1]-cells[i-1]===0){
                result[i] = 1;
            } else{
                result[i] = 0;
            }
        }
        if(day===0){ //将第一天后的状况作为循环周期开始
            startCells = result.join('');
        } else if(result.join('') === startCells){
            // 找到循环周期 将时间周期缩短到一个周期内
            N = N%day;
            day = 0;
            // console.log(day);
        }
        cells = result.join().split(',');
        day++;
    }
    return cells;
};
// var cells = [0,1,0,1,1,0,0,1], day = 117; // [0,1,1,1,0,1,0,0]
var cells = [1,0,0,1,0,0,1,0], day = 1000000000;
console.log(prisonAfterNDays_2(cells,day));